﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Timers;
using System.Web;

namespace TSharp.Core.AppBox.Handlers
{
    public class PerfmonHtttpHandler : BaseHttpHandler
    {
        const string HtmlFormat = @"
<!DOCTYPE html PUBLIC ""-//W3C//DTD XHTML 1.0 Transitional//EN"" ""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"">
<html xmlns=""http://www.w3.org/1999/xhtml"">
<head>
    <title>性能监视</title>
    <script type=""text/javascript"" src=""{0}/Scripts/jquery-1.4.2.js""></script>
</head>
<body>
<input type=""button"" value=""start"" onclick=""toggle(this)"" />
    <br />
    <img src=""{0}/tjb/ImageHandler.axd"" id=""MyImg"" alt=""流浪的小图片"" />
    <script type=""text/javascript"">
        $(function () {{
            
        }});
        function toggle(obj) {{
            if (obj.value == 'start') {{
                start();
                obj.value = ""stop"";
            }} else {{
                stop();
                obj.value = ""start"";
            }}
        }}
        var intervalHandle;
        function start() {{
            if (!intervalHandle)
                intervalHandle = setInterval(function () {{
                    $(""#MyImg"").attr(""src"", ""{0}/tjb/ImageHandler.axd?"" + new Date().getTime());
                }}, 1000);
        }}
        function stop() {{
            if(intervalHandle)
                clearInterval(intervalHandle);
            intervalHandle =null;
        }}
    </script>
</body>
</html>
";
        static PerfmonHtttpHandler()
        {
            InitializeWindowsPerformanceCounters();
        }
        public static string InstanceName = "TestSmartThreadPool";
        static private System.Diagnostics.PerformanceCounter _pcActiveThreads;
        static private System.Diagnostics.PerformanceCounter _pcInUseThreads;
        static private System.Diagnostics.PerformanceCounter _pcQueuedWorkItems;
        static private System.Diagnostics.PerformanceCounter _pcCompletedWorkItems;
        public static Dictionary<PerformanceCounter, IList<float>> Values;
        public static int xLength = 50;
        public static List<string> xValues = new List<string>();
      

        //static Random r = new Random();
        //private static System.Timers.Timer timer = new Timer(1000);

        static void InitializeWindowsPerformanceCounters()
        {


            for (int i = 0, n = xLength; i < n; i++)
                xValues.Add(i + "");

            Values = new Dictionary<PerformanceCounter, IList<float>>();
            _pcActiveThreads = new System.Diagnostics.PerformanceCounter();
            Values.Add(_pcActiveThreads, new List<float>());
            _pcInUseThreads = new System.Diagnostics.PerformanceCounter();
            Values.Add(_pcInUseThreads, new List<float>());
            _pcQueuedWorkItems = new System.Diagnostics.PerformanceCounter();
            Values.Add(_pcQueuedWorkItems, new List<float>());
            _pcCompletedWorkItems = new System.Diagnostics.PerformanceCounter();
           // Values.Add(_pcCompletedWorkItems, new List<float>());

            // 
            // pcActiveThreads
            // 
            _pcActiveThreads.CategoryName = "SmartThreadPool";
            _pcActiveThreads.CounterName = "Active threads";
            _pcActiveThreads.InstanceName = InstanceName;

            // 
            // pcInUseThreads
            // 
            _pcInUseThreads.CategoryName = "SmartThreadPool";
            _pcInUseThreads.CounterName = "In use threads";
            _pcInUseThreads.InstanceName = InstanceName;
            // 
            // pcQueuedWorkItems
            // 
            _pcQueuedWorkItems.CategoryName = "SmartThreadPool";
            _pcQueuedWorkItems.CounterName = "Work Items in queue";
            _pcQueuedWorkItems.InstanceName = InstanceName;
            // 
            // pcCompletedWorkItems
            // 
            _pcCompletedWorkItems.CategoryName = "SmartThreadPool";
            _pcCompletedWorkItems.CounterName = "Work Items processed";
            _pcCompletedWorkItems.InstanceName = InstanceName;
 

            //timer.Elapsed += new ElapsedEventHandler(timer_Elapsed);
            //timer.Start();
        }

        static void timer_Elapsed(object sender, ElapsedEventArgs e)
        {

            {
                try
                {

                    foreach (var p in Values)
                    {
                        var v = p.Value;
                        try
                        {
                            var counter = p.Key;
                            if (PerformanceCounterCategory.InstanceExists(counter.InstanceName, counter.CategoryName))
                            {
                                v.Add(p.Key.NextValue());
                            }
                            else
                            {
                                v.Add(9);
                                Debug.WriteLine(string.Format(@"无计数器：{0}\{1}\{2}", counter.InstanceName, counter.CategoryName, counter.CounterName));
                            }

                        }
                        catch (Exception ee)
                        {
                            Debug.WriteLine("计数器取值错误 >>> " + ee.Message);
                            //v.Add(r.Next(99));
                        }

                        if (v.Count > xLength)
                            v.RemoveAt(0);
                    }
                }
                catch (Exception ex)
                {
                    Debug.WriteLine("==== >>> " + ex.Message);
                }
            }
        }
        public PerfmonHtttpHandler(HttpContext context, string requestType, string url, string pathTranslated)
            : base(context, requestType, url, pathTranslated)
        { }


        public override void ProcessRequest(HttpContext context)
        {
            //  var stp = context.Session[""""] as SmartThreadPool;
            var p = context.Request.ApplicationPath;
            context.Response.Write(string.Format(HtmlFormat, p == "/" ? "" : p));
        }
    }
}